package com.zhengb.nettydemos.chapter4.timeserver;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by zhengbo on 2019/4/2.
 */
//@Slf4j
public class TimeClientHandler extends ChannelHandlerAdapter {

    private static Logger logger = LoggerFactory.getLogger(TimeClientHandler.class);

    private static AtomicInteger counter = new AtomicInteger(0);

    public TimeClientHandler() {

    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        byte[] req = ("request server time" + System.getProperty("line.separator")).getBytes();

        for (int i = 0; i < 100; i++) {
            ByteBuf message = Unpooled.buffer(req.length);
            message.writeBytes(req);
            ctx.writeAndFlush(message);
        }
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

//        ByteBuf buf = (ByteBuf) msg;
//        byte[] req = new byte[buf.readableBytes()];
//
//        buf.readBytes(req);
//        String body = new String(req, StandardCharsets.UTF_8);

        String body = (String) msg;

//        System.out.println("now time is:" + body + "");
        logger.info("now time is:{},the counter is:{}", body, counter.incrementAndGet());

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.error("{}", cause.getMessage());
        ctx.close();
    }
}
